var https = require('https');
var http = require('http');
var qs = require('querystring');

function ts(curTime){
    let t=new Date();
    if(curTime){
        t=new Date(curTime);
    }
    return t.toLocaleString(); 
}

const axios=require('axios').default;

//18032396357
var config={
    appId:'26159037',
    AppKey:'nmdgbkj9ksTn4260XjEqEOhW',//您的 Api Key
    AppSecret:'9fOGtFI1IrRuzRQu28rjzCbjAldvxhPI'//您的 Secret Key
};

var access_token='';
var expires_in=0;

const param = qs.stringify({
    'grant_type': 'client_credentials',
    'client_id': config.AppKey,
    'client_secret': config.AppSecret
});


//return: {"error_code","msg","data":access_token}
function getAccessToken(config){
    return new Promise(async function(resolve,reject){

        var sendurl='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+config.AppKey+'&client_secret='+config.AppSecret;

        try{
            const res=await axios.get(sendurl);
            if(res.status!=200){
                resolve({'error_code':-2,'msg':'request status error:'+res.statusText});
                return;
            }
            if(!res.data || !res.data.access_token){
                resolve({'error_code':-3,'msg':'getAccessToken return data error','data':res.data});
                return;
            }

            access_token=res.data.access_token;
            expires_in=res.data.expires_in;

            console.log(ts(),'appId',config.appId,'get access_token:',access_token,'expires_in=',expires_in,'秒');

            var curTime=new Date();
            var endTime=new Date(curTime.getTime()+expires_in);

            console.log('大约',ts(endTime),'到期');

            setTimeout(function(){

                console.log(ts(),'Timeout');

                getAccessToken(config);

            },expires_in-200);

            //data:{
            //access_token： 要获取的Access Token；
            //expires_in： Access Token的有效期(秒为单位，有效期30天)； 
            //}
            //
            
            
            resolve({'error_code':0,'msg':'ok','data':res.data.access_token});
        }catch(err){
            resolve({'error_code':-1,'msg':'Request error:'+err});
        }
    });
}

// var data={"group_id":group_id};
async function groupadd(config,data){
    return new Promise(async function(resolve,reject){
        if(!data || !data.group_id){
            resolve({'error_code':-1,'msg':'FAIL','data':{'error_code':-1,'error_msg':'param data error','data':{}}});
            return;
        }
        if(!config.access_token){
            var r=await getAccessToken(config);
            if(r.error_code!=0){
                resolve({'error_code':-1,'msg':'FAIL','data':{'error_code':-1,'error_msg':'getAccessToken error:'+r.msg}});
                return;
            } 
            config.access_token=r.data;
        }

        var url='https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/add';
        url+=("?access_token="+config.access_token);

        axios.post(url,data,{
            headers:{
                'Content-Type':'application/json; charset=UTF-8'
            }

        }).then(function(res){
            if(res.status!=200){
                resolve({'error_code':-2,'msg':'groupadd request statusCode error:'+res.status,data:{}});
                return;
            }

            if(res.data.error_code!=0){
                resolve({'error_code':res.data.error_code,'msg':res.data.error_msg,'data':res.data});
                return;
            }
            resolve({'error_code':0,'msg':res.data.msg,'data':res.data});

        }).catch(function(error){
            resolve({'error_code':-2,'msg':'request group add exception error:'+error,'data':{}});
        });
    }); 
}

//var data={"start":0,"length":100};//默认值
async function grouplist(config,data){
    return new Promise(async function(resolve,reject){
        if(!config.access_token){
            var r=await getAccessToken(config);
            if(r.error_code!=0){
                resolve({'error_code':-1,'msg':'FAIL','data':{'error_code':-1,'error_msg':'getAccessToken error:'+r.msg}});
                return;
            } 
            config.access_token=r.data;
        }

        var url='https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getlist';
        url+=("?access_token="+config.access_token);

        var obj={};
        if(data){
            obj=data;
        }

        axios.post(url,obj,{
            headers:{
                'Content-Type':'application/json; charset=UTF-8'
            }
        }).then(function(res){
            if(res.status!=200){
                resolve({'error_code':-2,'msg':'grouplist request statusCode error:'+res.status,data:{}});
                return;
            }

            if(res.data.error_code!=0){
                resolve({'error_code':res.data.error_code,'msg':res.data.error_msg,'data':res.data});
                return;
            }
            resolve({'error_code':0,'msg':'ok','data':res.data});

        }).catch(function(error){
            resolve({'error_code':-2,'msg':'request grouplist error'+error});
        });
    }); 
}

//config={"appId","AppKey","AppSecret"}
//data={"group_id":groupid}
//apiUrl='/faceset/group/delete';
async function common(config,apiUrl,data){
    return new Promise(async function(resolve,reject){
        if(!config.access_token){
            var r=await getAccessToken(config);
            if(r.error_code!=0){
                resolve({'error_code':-1,'msg':'FAIL','data':{'error_code':-1,'error_msg':'getAccessToken error:'+r.msg}});
                return;
            } 
            config.access_token=r.data;
        }

        var url='https://aip.baidubce.com/rest/2.0/face/v3'+apiUrl;
        url+=("?access_token="+config.access_token);

        //console.log("common url:",url);

        var obj={};
        if(data){
            obj=data;
        }

        axios.post(url,obj,{
            headers:{
                'Content-Type':'application/json; charset=UTF-8'
            }
        }).then(function(res){
            if(res.status!=200){
                resolve({'error_code':-2,'msg':'FAIL','data':{'error_code':-2,'error_msg':'request statusCode error:'+res.status,data:{}}});
                return;
            }

            if(res.data.error_code!=0){
                resolve({'error_code':res.data.error_code,'msg':'FAIL','data':res.data});
                return;
            }
            resolve({'error_code':0,'msg':'SUCCESS','data':res.data});

        }).catch(function(error){
            resolve({'error_code':-2,'msg':'FAIL','data':{'error_code':-3,'error_msg':'exception:'+error}});
        });
    }); 
}

async function main(){
    //r=await getAccessToken(config);
    //console.log(r);

    /*
    data={'group_id':'groupTest004'};
    r=await common(config,'faceset/group/add',data);
    if(r.error_code!=0){
        console.log(r);
        return;
    }
    */

    data={'group_id':'groupTest004'};
    r=await common(config,'/faceset/group/delete',data);
    if(r.error_code!=0){
        console.log(r);
        return;
    }

    r=await common(config,'/faceset/group/getlist');
    if(r.error_code==0){
        console.log('group list:');
        console.log(r.data.result.group_id_list);
    }else{
        console.log(r.msg);
    }

}
//main();

module.exports.common= common;

